/*
** File name:		window_opcode.c
** Brief: 
** COPYRIGHT(C) gkt 2020 
** ------------------------------------------------------- 
** Module Information: 
** 
** Revision History -------------------------------------- 
** ------------------------------------------------------- 
**	Date 		Version		Action				Author   
** ------------------------------------------------------- 
**	2020-8-11 	1.0			Created				liwenjie   
** 
*/ 

/* Includes -----------------------------------------------------*/
#include "gkt_debug.h"
#include "gkt_rfid.h"
#include "window_opcode.h"

#define WINDOW_OPCODE_MAGIC	0x4D6D1F4C

typedef struct {
	uint32_t	magic; 
	uint32_t	opcode;
	uint32_t	reserved[2];
} window_opcode_header_s;

/* Global Variables ---------------------------------------------*/
/* Macro --------------------------------------------------------*/
static uint8_t s_card_key[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

/* Extern Functions ---------------------------------------------*/
/* Static Functions ---------------------------------------------*/
/* Functions ----------------------------------------------------*/

static int window_opcode_read_block_data(
				gkt_rfid_info_s *rfid_info,
				uint32_t block_index, void *buffer)
{
	uint32_t block_addr;
	int retval;

	block_addr = block_index*4 + 2;
	retval = gkt_rfid_auth_state(GKT_RFID_AUTH_A_KEY,
					(uint8_t)block_addr, rfid_info->id, 
					s_card_key);
	if (GKT_SUCCESS == retval)
		retval = gkt_rfid_read(block_addr, buffer);

	return retval;
}

uint32_t window_opcode_fetch(gkt_rfid_info_s *rfid_info)
{
	window_opcode_header_s opcode_header;
	uint32_t block_index, opcode;
	int retval;

	opcode = 0;

	/* read image header */
	block_index = 15;
	retval = window_opcode_read_block_data(rfid_info,
					block_index, (void *)&opcode_header);
	if (GKT_SUCCESS == retval) {
		gkt_trace("window_opcode: magic(0x%08x), opcode(%u)\n",
				opcode_header.magic, opcode_header.opcode);
		/* correct image header? */
		opcode = (WINDOW_OPCODE_MAGIC == opcode_header.magic) ? 
					opcode_header.opcode : 0;
	}

	return opcode;
}

/* end */

